
package com.jf.cloud.multishop.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.auth.feign.AccountFeignClient;
import com.jf.cloud.api.auth.vo.AuthAccountVO;
import com.jf.cloud.api.biz.feign.NotifyFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.SendTypeEnum;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PrincipalUtil;
import com.jf.cloud.multishop.dto.ShopUserDTO;
import com.jf.cloud.multishop.service.ShopDetailService;
import com.jf.cloud.multishop.service.ShopUserService;
import com.jf.cloud.multishop.vo.ShopUserSimpleVO;
import com.jf.cloud.multishop.vo.ShopUserVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author zz
 * @date 2020/09/02
 */
@RequestMapping(value = "/m/shop_user")
@RestController
@Tag(name = "店铺用户信息")
public class ShopUserController {

    @Value("${jfcloud.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private ShopUserService shopUserService;

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private NotifyFeignClient notifyFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    @GetMapping("/info")
    @Operation(summary = "登陆店铺用户信息" , description = "获取当前登陆店铺用户的用户信息")
    public ServerResponseEntity<ShopUserSimpleVO> info() {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        ShopUserSimpleVO shopUserSimple = new ShopUserSimpleVO();
        shopUserSimple.setIsAdmin(userInfoInTokenBO.getIsAdmin());
        shopUserSimple.setUserName(userInfoInTokenBO.getUserName());
        if (!Objects.equals(userInfoInTokenBO.getTenantId(), Constant.DEFAULT_SHOP_ID)) {
            ShopDetailVO shopDetail = shopDetailService.getByShopId(userInfoInTokenBO.getTenantId());
            shopUserSimple.setAvatar(shopDetail.getShopLogo());
            shopUserSimple.setShopName(shopDetail.getShopName());
        }
        return ServerResponseEntity.success(shopUserSimple);
    }

    @GetMapping("/page")
    @Operation(summary = "店铺用户列表" , description = "获取店铺用户列表")
    public ServerResponseEntity<PageVO<ShopUserVO>> page(@Valid PageDTO pageDTO, @ParameterObject ShopUserDTO shopUserDTO) {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        shopUserDTO.setShopId(userInfoInTokenBO.getTenantId());
        PageVO<ShopUserVO> shopUserPage = shopUserService.pageByShopId(pageDTO, shopUserDTO);
        return ServerResponseEntity.success(shopUserPage);
    }

    @GetMapping
    @Operation(summary = "获取店铺用户信息" , description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<ShopUserVO> detail(@ParameterObject @RequestParam Long shopUserId) {
        return ServerResponseEntity.success(shopUserService.getByUserId(shopUserId));
    }

    @PostMapping
    @Operation(summary = "保存店铺用户信息" , description = "保存店铺用户信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody ShopUserDTO shopUserDTO) {
        if (!PrincipalUtil.isMobile(shopUserDTO.getPhone())) {
            throw new LuckException("请输入正确格式的手机号!");
        }
        if (StrUtil.isBlank(shopUserDTO.getValidCode())) {
            throw new LuckException("请输入验证码");
        }
        shopUserDTO.setShopId(AuthUserContext.get().getTenantId());
        checkCode(shopUserDTO);
        shopUserService.saveAccount(shopUserDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新店铺用户信息" , description = "更新店铺用户信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody ShopUserDTO shopUserDTO) {
        // 暂时的home账号id
        Long home = 109707L;
        if (Objects.equals(shopUserDTO.getShopUserId(), home) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户信息");
        }
        ShopUserVO dbShopUser = shopUserService.getByUserId(shopUserDTO.getShopUserId());
        if (!Objects.equals(dbShopUser.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (!PrincipalUtil.isMobile(shopUserDTO.getPhone())) {
            throw new LuckException("请输入正确格式的手机号!");
        }
        // 如果修改了手机号码，就需要校验验证码
        if (!StrUtil.equals(dbShopUser.getPhone(),shopUserDTO.getPhone())) {
            if (StrUtil.isBlank(shopUserDTO.getValidCode())) {
                throw new LuckException("修改了手机号，请输入验证码校验");
            }
            checkCode(shopUserDTO);
        }
        shopUserDTO.setShopId(dbShopUser.getShopId());
        ServerResponseEntity<AuthAccountVO> authAccountEntity = accountFeignClient.getByUserIdAndType(dbShopUser.getShopUserId(), SysTypeEnum.MULTISHOP.value());
        if (authAccountEntity.isFail()) {
            throw new LuckException(authAccountEntity.getMsg());
        }
        AuthAccountVO authAccountVO = authAccountEntity.getData();
        if (Objects.equals(authAccountVO.getIsAdmin(), 1) && !Objects.equals(dbShopUser.getShopUserId(), AuthUserContext.get().getUserId())) {
            return ServerResponseEntity.showFailMsg("您没有权限修改管理员信息");
        }
        shopUserService.updateAccount(shopUserDTO);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除店铺用户信息" , description = "根据店铺用户id删除店铺用户信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long shopUserId) {
        UserInfoInTokenBO userInfoInToken = AuthUserContext.get();
        ShopUserVO dbShopUser = shopUserService.getByUserId(shopUserId);
        if (!Objects.equals(dbShopUser.getShopId(), userInfoInToken.getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        } else if (Objects.equals(userInfoInToken.getUserId(), shopUserId)) {
            throw new LuckException("您正在使用当前账号，无法进行删除操作");
        }
        shopUserService.deleteById(shopUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/verify_account")
    @Operation(summary = "验证店铺账号" , description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<Boolean> verifyAccount(@ParameterObject ShopUserDTO shopUserDTO) {
        // 验证手机号/邮箱/用户名在数据库中是否已经存在
        return shopUserService.verifyShopUserAccount(shopUserDTO);
    }

    /**
     * 校验验证码
     * @param shopUserDTO
     * @return
     */
    private void checkCode(ShopUserDTO shopUserDTO) {
        // 手机号验证码
        String phone = shopUserDTO.getPhone();
        if (StrUtil.isNotBlank(phone)) {
            ServerResponseEntity<Boolean> sendNotifyResponse = notifyFeignClient.checkValidCode(phone, shopUserDTO.getValidCode(), SendTypeEnum.VALID);
            Boolean data = sendNotifyResponse.getData();
            if (Objects.equals(sendNotifyResponse.getCode(), ResponseEnum.OK.value()) && Objects.nonNull(data) && !data) {
                throw new LuckException("验证码有误或已过期");
            }
        }
        //邮箱验证码
    }
}
